package com.haiyou.common.spring.listener;

import java.util.List;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;
import com.haiyou.common.event.asyc.AsyncEventBuses;
import com.haiyou.common.spring.component.LifecycleableComponent;
import com.haiyou.common.spring.event.SpringApplicationContextDestoriedEvent;
import com.haiyou.common.spring.util.SpringUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * 
 * @Description: spring 关闭监听
 * @author xingyuan
 * @date 2022年5月17日 下午8:38:43
 */
@Slf4j
@Component
public class SpringContextClosedListener implements ApplicationListener<ContextClosedEvent>{
	
	@Override
	public void onApplicationEvent(ContextClosedEvent event) {
		
		if(log.isDebugEnabled()) {
			log.debug("=======spring content close===========");
		}
		
		//需要生命周期管理得bean
		List<LifecycleableComponent> lifecycles = Lists
				.newArrayList(SpringUtil.getBeansOfType(LifecycleableComponent.class).values());
	
		for (LifecycleableComponent lifecycleableComponent : lifecycles) {
			if(log.isDebugEnabled()) {
				log.info("============={},执行关闭方法=========",lifecycleableComponent.getClass().getSimpleName());
			}
			lifecycleableComponent.stop();
			if(log.isDebugEnabled()) {
				log.info("============={},关闭完成=========",lifecycleableComponent.getClass().getSimpleName());
			}
		}
		
		AsyncEventBuses.getInstance().postEvent(new SpringApplicationContextDestoriedEvent());
	}

}
